package com.summer.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SocketChannelCase1 {
	public static void main(String[] args) throws IOException, InterruptedException {
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
 
		while (!socketChannel.finishConnect()) {  
			System.out.println("connect");
            Thread.sleep(10);  
        }
		
		String newData = "GET http://127.0.0.1:9999 HTTP/1.1\r\n";

		ByteBuffer buf = ByteBuffer.allocate(48);
		buf.clear();
		buf.put(newData.getBytes());

		buf.flip();

		while(buf.hasRemaining()) {
			socketChannel.write(buf);
		}

		boolean stop = true;
		ByteBuffer readBuf = ByteBuffer.allocate(1024);
		
		while(stop){
			readBuf.clear();
			stop = socketChannel.read(readBuf) != -1;
			
			readBuf.flip();
			byte[] body = new byte[readBuf.limit()];
			readBuf.get(body, 0, body.length);
			System.out.println("body:"+new String(body));
		}
		
		socketChannel.close();
	}
}
